<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="./layui/css/layui.css">
    <script src="./layui/layui.js"></script>
    <script src="./js/global.js"></script>
    <style>
        .layui-table-page{
            text-align: center;
        }
    </style>
</head>
<body>
    <!-- 多条件查询 -->
    <form class="layui-form">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: auto;">用户名</label>
                <div class="layui-input-inline">
                    <input type="text" id="username_search" placeholder="请输入用户名" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: auto;">姓名</label>
                <div class="layui-input-inline">
                    <input type="text" id="name_search" placeholder="姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: auto;">状态</label>
                <div class="layui-input-inline">
                  <select id="status_search" lay-verify="required">
                    <option value="">请选择状态</option>
                    <option value="1">启用</option>
                    <option value="0">禁用</option>
                  </select>
                </div>
              </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn layui-btn-normal" onclick="doSearch()">查询</button>
            </div>
        </div>
    </form>

    <table id="userList">
    </table>

    <!-- 修改弹出层 -->
    <div id="modifyLayer" style="display: none; margin-top: 30px;margin-right: 40px; width: 400px;">
        <form class="layui-form" lay-filter="formModify" id="modifyForm">
            <div class="layui-form-item">
                <label class="layui-form-label">编号</label>
                <div class="layui-input-block">
                  <input type="text" name="id" id="id" required lay-verify="required" placeholder="请输入编号" class="layui-input" readonly>
                </div>
              </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" id="username" required lay-verify="required" placeholder="请输入用户名"
                        class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="name" required lay-verify="required" placeholder="请输入姓名"
                        class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input type="text" name="age" id="age" required lay-verify="required" placeholder="请输入年龄"
                        class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">头像</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn layui-btn-normal" id="avatar">
                        <i class="layui-icon">&#xe67c;</i>上传图片
                    </button>
                    <input type="hidden" id="avatarPath" name="avatar">
                    <img src="" id="avatarImg" style="width: 40px; height: 40px; border-radius: 50%; display: none;">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit lay-filter="modify"
                        style="width: 180px;">修&nbsp;&nbsp;&nbsp;&nbsp;改</button>
                </div>
            </div>
        </form>
    </div>

    <script>
        layui.use(['layer', 'laypage', 'form', 'upload', 'table'], function () {
            var layer = layui.layer
            var laypage = layui.laypage;
            var $ = layui.jquery
            var form = layui.form
            var upload = layui.upload;
            var table = layui.table;

            form.render();

            // 渲染表格
            table.render({
                elem: '#userList'
                ,url: BASE_URL + '/user/list' //数据接口
                // ,page: true //开启分页
                ,page:{
                    layout:['count','prev','page','next','limit','skip','refresh'] // 自定义分页布局
                }
                ,limit:5
                ,limits:[5,10,15]
                ,cols: [[ //表头
                    {field: 'id', title: '序号', align:'center', type:'numbers', sort:true, width:80}
                    ,{field: 'username', title: '用户名', align:'center'}
                    ,{field: 'name', title: '姓名', align:'center'}
                    ,{field: 'age', title: '年龄', align:'center'} 
                    ,{field: 'status', title: '状态', align:'center',templet:function(data){
                        if(data.status == 1){
                            return `<input type="checkbox" lay-skin="switch" lay-text="启用|禁用" lay-filter="status" checked value="${data.id}">`
                        }else{
                            return `<input type="checkbox" lay-skin="switch" lay-text="启用|禁用" lay-filter="status" value="${data.id}">`
                        }
                    }}
                    ,{field: 'registertime', title: '注册时间', align:'center'}
                    ,{field: 'id', title: '操作', align:'center', width:220 ,templet:function(data){
                        var str = `<button class="layui-btn layui-btn-sm layui-btn-normal" onclick="doModify(${data.id})">编辑</button>`
                        if(data.username != 'admin'){
                            str += `
                            <button class="layui-btn layui-btn-sm layui-btn-danger" onclick="doDelete(${data.id})">删除</button>
                            <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="resetPassword(${data.id})">重置密码</button>
                            `
                        }
                        return str;
                    }}
                ]]
            });

            //执行实例
            var uploadInst = upload.render({
                elem: '#avatar', //绑定元素
                url: BASE_URL + '/upload', //上传接口
                done: function(res){  //上传完毕回调
                    console.log(res)
                    $('#avatarPath').val(res.data)
                    $('#avatarImg').attr('src', BASE_URL + res.data).show()
                    // 鼠标点击图片显示大图
                    $('#avatarImg').click(function(){
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            area: '600px',
                            skin: 'layui-layer-nobg', //没有背景色
                            shadeClose: true,
                            content: '<img src="'+ BASE_URL + res.data +'" style="width: 600px; height: 600px;">'
                        });
                    })
                },
                error: function(err){  //请求异常回调
                   layer.msg('上传失败', {icon: 5})
                }
            });

            // 监听开关switch被点击
            form.on('switch(status)', function(data){
                // console.log(data.elem.checked); //开关是否开启，true或者false
                // console.log(data.value); //开关value值
                $.ajax({
                    url: BASE_URL + '/user/modifyStatus',
                    data:{
                        id:data.value,
                        status:data.elem.checked ? 1 : 0
                    },
                    dataType:'json',
                    success:function(res){
                        if(res.status == 200){
                            layer.msg('状态更新成功！',{icon:1})
                        }else{
                            layer.msg('状态更新失败！',{icon:2})
                        }
                    }
                })
            });  
    
        });

        /**
         * 删除
         */
        function doDelete(id) {
            layui.use('layer', function () {
                var layer = layui.layer
                var $ = layui.jquery
                layer.confirm('确定要删除吗', { icon: 3, title: '提示信息' }, function (index) {
                    $.ajax({
                        url: BASE_URL + '/user/removeById',
                        data: {id},
                        dataType: 'json',
                        success: function (res) {
                            if (res.status == 200) {
                                layer.msg('删除成功！', { icon: 1 })
                                // doSearch()
                                layui.table.reload('userList')
                            } else {
                                layer.msg('删除失败！', { icon: 2 })
                            }
                        }
                    })
                    
                    layer.close(index)
                });
            })
        }

        /**
         * 修改
         */
        function doModify(id) {
            layui.use(['layer', 'form', 'table'], function () {
                var layer = layui.layer
                var $ = layui.jquery
                var form = layui.form

                // 获取用户信息
                $.ajax({
                    url: BASE_URL + '/user/findById',
                    data:{id},
                    dataType:'json',
                    success:function(res){
                        // 方式1：给每个input赋值
                        // $('#id').val(res.data.id)
                        // $('#username').val(res.data.username)
                        // $('#name').val(res.data.name)
                        // $('#age').val(res.data.age)
                        $('#avatarImg').attr('src',BASE_URL + res.data.avatar).show()
                        // 方式2：使用layui提供的表单赋值
                        form.val('formModify', res.data)

                        layer.open({
                            type: 1,
                            title: '修改管理员信息',
                            content: $('#modifyLayer'),
                        })
                    }
                })

                // 监听表单提交
                form.on('submit(modify)',function(data){
                    $.ajax({
                        type:'post',
                        url: BASE_URL + '/user/modify',
                        data:data.field,
                        dataType:'json',
                        success:function(res){
                            if(res.status == 200){
                                layer.msg('修改成功！',{icon:1,time:1000},function(){
                                    $('#modifyForm')[0].reset() // 清空表单
                                    layer.closeAll()
                                    layui.table.reload('userList')
                                })
                            }else{
                                layer.msg('修改失败！',{icon:2})
                            }
                        }
                    })
                })
            })
        }

        /**
         * 按条件搜索
         */ 
        function doSearch(){
            layui.use(['table'],function(){
                var table = layui.table
                var $ = layui.jquery

                table.reload('userList', {
                    where:{ //设定异步数据接口的额外参数
                        username:$('#username_search').val(),
                        name:$('#name_search').val(),
                        status:$('#status_search').val(),
                    }
                })
            })
        }

        /**
         * 重置密码
         */
        function resetPassword(id){
            layui.use(['layer'],function(){
                var layer = layui.layer
                var $ = layui.jquery

                $.ajax({
                    url: BASE_URL + '/user/resetPassword',
                    data:{id},
                    dataType:'json',
                    success:function(res){
                        if(res.status == 200){
                            layer.msg('重置密码成功！',{icon:1})
                        }else{
                            layer.msg('重置密码失败！',{icon:2})
                        }
                    }
                })
            })
        }
    </script>
</body>
</html>